#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <set>

#define flr(x,l,r) for (int x = l; x <= r; ++ x)
#define frl(x,r,l) for (int x = r; x >= l; -- x)
#define fmp(x,t) for (int x = h[t]; ~x; x = ne[x])
#define LL long long 
#define mt memset
#define my memcpy
#define szf sizeof
#define INF 0x3f3f3f3f
#define in(x) scanf("%d", &x)
#define out(x) printf("%d", x)
#define inll(x) scanf("%lld", &x)
#define outll(x) printf("%lld", x)
#define pn printf("\n")
#define con continue
#define bk break
#define vc vector
#define pb push_back
#define sz size
#define PII pair<int, int>
#define x first
#define y second
#define P_q priority_queue
#define ft front
#define pf push_front
#define popf pop_front
#define it insert
#define ct count

using namespace std;

const int N = 6;

char g[N][N], bg[N][N];

void turn(int x, int y) {
    int dx[5] = {-1, 0, 1, 0, 0}, dy[5] = {0, 1, 0, -1, 0};
    
    flr (i, 0, 4) {
        int a = x + dx[i], b = y + dy[i];
        if (a < 0 || a >= 5 || b < 0 || b >= 5) con;
        g[a][b] ^= 1;
    }
}

int main() {
    int T;
    cin >> T;
    
    while (T -- ) {
        flr (i, 0, 4) cin >> bg[i];
        
        int res = 10;
        flr (op, 0, 31) {
            int cnt = 0;
            my(g, bg, szf g);
            
            flr (i, 0, 4) 
                if (op >> i & 1) {
                    turn(0, i);
                    cnt ++ ;
                }
                
            flr (i, 0, 3)
                flr (j, 0, 4)
                    if (g[i][j] == '0') {
                        turn(i + 1, j);
                        cnt ++ ;
                    }
            
            bool flag = true;
            flr (i, 0, 4)
                if (g[4][i] == '0') {
                    flag = false;
                    bk;
                }
            
            if (flag && res > cnt) res = min(res, cnt);
        }
        
        if (res > 6) puts("-1");
        else out(res), pn;
    }
    
    return 0;
}